package com.wlz.maotai.rest;

import com.wlz.maotai.msg.RobMaotaiMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 *
 */

@Slf4j
@Component
public class Http1Test implements ApplicationRunner {



    @Override
    public void run(ApplicationArguments args) throws Exception {
        String json = "{\"pid\":\"4019862523568\",\"businessTag\":\"zhan\",\"hash\":\"Ua3mGVbdz\",\"zhanId\":\"1435031\",\"preview\":false,\"isTsa\":false,\"tsa\":false,\"isH5\":true,\"businessParams\":{},\"isCutToImg\":false,\"drawId\":\"\",\"newSolution\":true,\"zhanParams\":{\"cuid\":\"19733053891lfnrosaov\"}}";

        String path = "https://4019862523568.zhan.n.weimob.com/api3/zhan/xapp/page";

        log.error("error");
        log.warn("warn");
        log.info("info");

        while (true) {
            Thread.sleep(500);
            try {
                log.info("resquest start .............................");
                String response = postJSON(path, json);
                log.info("response rersult:" + response);
                if (!response.contains("今日已约完，未成功提交预约信息")) {
                    RobMaotaiMsg.sendMsg();
                }
            } catch (Exception e) {
                log.error("postJSON error:", e);
            }
        }
    }

    // 发送POST请求（JSON形式）
    public static String postJSON(String path, String json) throws Exception {
        StringEntity entity = new StringEntity(json, Charsets.UTF_8);
        return postRequest(path, "application/json", entity);
    }

    /**
     *  Content-Type: application/json; charset=utf-8
     * User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
     * cookie: rprm_cuid=9700263835hog37vjfvg; saas.express.session=s%3AsK_1QJOLuf-hHTdli24Aj8S3V3qCkbfu.S5GyOnkFpIN46xbgj2uPJjw2fnnbDVX3tn8bjgYqGO8
     * Etag: W/"194a-Iq7k0jHDUovSLMlUWEcN5OcA9jw"
     * referer: https://4019862523568.zhan.n.weimob.com/saas/zhan/4019862523568/1435031/Ua3mGVbdz?last_pageid=3177644
     * idc: sh4
     * @param path
     * @param mediaType
     * @param entity
     * @return
     * @throws Exception
     */

    // 发送POST请求
    public static String postRequest(String path, String mediaType, HttpEntity entity) throws Exception {
        log.debug("[postRequest] resourceUrl: {}", path);
        HttpPost post = new HttpPost(path);
        post.addHeader("Content-Type", mediaType);
        post.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36");
        post.addHeader("cookie", "rprm_cuid=9700263835hog37vjfvg; saas.express.session=s%3AsK_1QJOLuf-hHTdli24Aj8S3V3qCkbfu.S5GyOnkFpIN46xbgj2uPJjw2fnnbDVX3tn8bjgYqGO8");
        post.addHeader("Etag", "W/\\\"194a-Iq7k0jHDUovSLMlUWEcN5OcA9jw\\\"");
        post.addHeader("referer", "https://4019862523568.zhan.n.weimob.com/saas/zhan/4019862523568/1435031/Ua3mGVbdz?last_pageid=3177644");
        post.setEntity(entity);
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400)
                throw new Exception(EntityUtils.toString(response.getEntity()));
            return EntityUtils.toString(response.getEntity());
        }
        catch (ClientProtocolException e) {
            throw new Exception("postRequest -- Client protocol exception!", e);
        }
        catch (IOException e) {
            throw new Exception("postRequest -- IO error!", e);
        }
        finally {
            post.releaseConnection();
        }
    }


    public static void main(String[] args) throws Exception {
        String json = "{\"pid\":\"4019862523568\",\"businessTag\":\"zhan\",\"hash\":\"Ua3mGVbdz\",\"zhanId\":\"1435031\",\"preview\":false,\"isTsa\":false,\"tsa\":false,\"isH5\":true,\"businessParams\":{},\"isCutToImg\":false,\"drawId\":\"\",\"newSolution\":true,\"zhanParams\":{\"cuid\":\"19733053891lfnrosaov\"}}";

        String path = "https://4019862523568.zhan.n.weimob.com/api3/zhan/xapp/page";

        while (true) {
            try {
                String s = postJSON(path, json);
                if (!s.contains("今日已约完，未成功提交预约信息")) {
                    RobMaotaiMsg.sendMsg();
                }
            } catch (Exception e) {
                log.error("postJSON error:", e);
            }
        }

    }

}
